package com.gudaomai.ekproject.web;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.Page;
import com.gudaomai.ekproject.entity.PageInput;
import com.gudaomai.ekproject.entity.RetEntity;
import com.gudaomai.ekproject.service.IPageService;
import com.gudaomai.ekproject.service.IProjectService;
import com.gudaomai.ekproject.web.BaseController;

/**
 * <p>
 * 页面 前端控制器
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@RestController
@RequestMapping("/ekproject/page")
public class PageController extends BaseController {

	@Autowired
	IProjectService projectServ;
	@Autowired
	IPageService pageServ;
	@Autowired
	protected MessageSource messageSource;

	/**
	 * TODO:complete 添加页面 1.判断页面名称是否已经存在 2.添加页面
	 * 
	 * @param pageInput
	 * @return
	 * @author xiaosong
	 * @throws CommonException
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public Page addPage(@RequestBody PageInput pageInput) throws CommonException {

		// 检测工程名是否存在[此操作前存在校验是否为空等,所以不必校验pro.getName是否为空]
		Page page = null;
		if (pageServ.isExist(pageInput.getName())) {
			// 数据库存在该记录，拒绝执行插入操作
			// 设置返回代码为201 状态信息：ret_project_add_already_exist
			throw new CommonException(CommonConstant.RESULT_CODE_CREATED, MsgConstant.RET_PROJECT_ADD_ALREADY_EXIST);
		} else {
			// 数据库不存在该条记录，执行插入操作
			// 设置该记录的id_
			page = new Page();
			BeanUtils.copyProperties(pageInput, page);
			page.setId(IdWorker.get32UUID());
			// 设置pid
			page.setPid("0");
			// 设置每个工程所有页面的顺序
			int order = pageServ.getSortOrder(pageInput.getProjectId());
			page.setSort(order + 1);
			// 执行插入操作
			pageServ.insert(page);
			// 设置返回代码200 状态信息：ret_project_add_success
			page.setRetCode(CommonConstant.RESULT_CODE_OK);
			page.setRetMessage(MsgConstant.RET_PROJECT_ADD_SUCCESS);
		}

		return page;
	}

	/**
	 * TODO:complete 根据id进行更新 注意部分字段不能为空，需要做输入检查
	 * 
	 * @param pro
	 * @return
	 * @throws CommonException
	 */
	@RequestMapping(value = "/", method = RequestMethod.PUT)
	public RetEntity updatePage(@RequestBody @Validated PageInput pageInput) throws CommonException {

		RetEntity retEntity = new RetEntity();

		Page page = new Page();
		BeanUtils.copyProperties(pageInput, page);
		boolean updated = pageServ.updateById(page);

		if (updated) {
			// 更新成功，设置状态码为200 @see CommonConstant
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PROJECT_UPDATE_SUCCESS);
		} else {
			// 更新失败，设置状态码为304 未修改 @see CommonConstant
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PROJECT_UPDATE_FAILURE));
		}

		return retEntity;
	}

	/**
	 * TODO:complete 根据id进行删除
	 * 
	 * @param pro
	 * @return
	 * @throws CommonException
	 */
	@RequestMapping(value = "/id/{id}", method = RequestMethod.DELETE)
	public RetEntity delPage(@PathVariable("id") String id) throws CommonException {

		RetEntity retEntity = new RetEntity();

		// 通过id来进行删除
		boolean deleted = pageServ.deleteById(id);
		// 对删除结果进行判断
		if (deleted) {
			// 删除成功，返回状态码200，状态信息，ret_page_delete_success
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PAGE_DELETE_SUCCESS);
		} else {
			// 删除失败，返回状态码304，状态信息，ret_page_delete_failure
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PAGE_DELETE_FAILURE));
		}

		return retEntity;
	}

	/**
	 * TODO:complete 将页面位置上移,对sort的更改
	 * 
	 * @author xiaosong
	 * 
	 * @param pro
	 * @return
	 * @throws CommonException
	 */
	@RequestMapping(value = "/moveUp", method = RequestMethod.PUT)
	public RetEntity moveUp(@RequestParam("id") String id) throws CommonException {

		RetEntity retEntity = new RetEntity();

		// 获取当前Page
		Page currentPage = pageServ.getPageById(id);
		// 获取当前Page的sort
		int currentPageSort = currentPage.getSort();
		// 获取同级上一个Page,获取不到抛出异常
		Page upPage = pageServ.getUpPageById(id);
		int upPageSort = upPage.getSort();

		currentPage.setSort(upPageSort);
		upPage.setSort(currentPageSort);

		// 执行update操作
		boolean updatedC = pageServ.updateById(currentPage);
		boolean updatedU = pageServ.updateById(upPage);

		if (updatedC && updatedU) {
			// 设置返回状态码200，状态信息 ret_page_move_up_success
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PAGE_MOVE_UP_SUCCESS);
		} else {
			// 设置返回状态码304，状态信息 ret_page_move_down_failure
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED, MsgConstant.RET_PAGE_MOVE_UP_FAILURE);
		}

		return retEntity;
	}

	/**
	 * TODO:complete 将页面位置下移,对sort的更改
	 * 
	 * @return
	 * @throws CommonException
	 */
	@RequestMapping(value = "/moveDown", method = RequestMethod.PUT)
	public RetEntity moveDown(@RequestParam("id") String id) throws CommonException {
		RetEntity retEntity = new RetEntity();

		// 获取当前Page
		Page currentPage = pageServ.getPageById(id);
		// 获取当前Page的sort
		int currentPageSort = currentPage.getSort();
		// 获取同级下一个Page,获取不到抛出异常
		Page downPage = pageServ.getDownPageById(id);
		int downPageSort = downPage.getSort();

		// 对这两个记录进行更新
		currentPage.setSort(downPageSort);
		downPage.setSort(currentPageSort);

		// 执行update操作
		boolean updatedC = pageServ.updateById(currentPage);
		boolean updatedU = pageServ.updateById(downPage);

		if (updatedC && updatedU) {
			// 设置返回状态码200，状态信息 ret_page_move_down_success
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PAGE_MOVE_DOWN_SUCCESS);
		} else {
			// 设置返回状态码304，状态信息 ret_page_move_down_failure
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED, MsgConstant.RET_PAGE_MOVE_DOWN_FAILURE);
		}

		return retEntity;
	}

	/**
	 * TODO:complete 将对象页面移动到指定页面的下面 1.判断pid是否存在 2.更新页面的pid为目标值
	 * 
	 * @return
	 * @throws CommonException
	 */
	@RequestMapping(value = "/moveTo", method = RequestMethod.PUT)
	public RetEntity moveTo(@RequestParam("id") String id, @RequestParam("pid") String pid) throws CommonException {

		RetEntity retEntity = new RetEntity();

		// 使用getPageById获取page，查询不到抛出异常
		Page pageSrc = pageServ.getPageById(id);
		Page parentPage = pageServ.selectById(pid);
		if (parentPage == null) {
			// 如果父页面不存在,则抛出异常
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PAGE_MOVE_TO_FAILURE));
		} else {
			pageSrc.setPid(parentPage.getId());
			// 将所有数据进行更新操作
			pageServ.updateById(pageSrc);
			// 设置返回状态码200，状态信息 ret_page_move_to_success
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PAGE_MOVE_TO_SUCCESS);
		}

		return retEntity;
	}

}
